import os
import PyPDF2

def open_file(filename):
    """打开文件，处理文件打开异常"""
    try:
        if filename.endswith(".pdf"):
            with open(filename, "rb") as f:
                reader = PyPDF2.PdfReader(f)
                content = ""
                for page in reader.pages:
                    content += page.extract_text()
        else:
            with open(filename, "r", encoding="utf-8") as f:
                content = f.read()
        return content
    except FileNotFoundError:
        print("文件未找到：", filename)
        return None
    except UnicodeDecodeError:
        print("文件编码错误，请尝试使用其他编码方式。")
        return None
    except Exception as e:
        print("读取文件时出错：", e)
        return None

def count_lines(file_content):
    """统计行数"""
    if not file_content:
        return 0
    return len(file_content.splitlines())

def count_words(file_content):
    """统计单词数"""
    if not file_content:
        return 0
    words = file_content.split()
    return len(words)

def count_characters(file_content):
    """统计字符数"""
    if not file_content:
        return 0
    return len(file_content)

def display_results(lines, words, characters):
    """输出结果，展示统计数据"""
    print("行数：", lines)
    print("单词数：", words)
    print("字符数：", characters)

# 主程序
if __name__ == "__main__":
    filename = input("请输入文件名：")
    filepath = None
    for root, _, files in os.walk("."):
        if filename in files:
            filepath = os.path.join(root, filename)
            break

    if filepath:
        file_content = open_file(filepath)
        if file_content:
            lines = count_lines(file_content)
            words = count_words(file_content)
            characters = count_characters(file_content)
            display_results(lines, words, characters)
    else:
        print(f"文件 {filename} 未找到。")
